package com.tool4j.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tool4j.entity.AiChatLog;
import com.tool4j.entity.AiSessionLog;
import com.tool4j.entity.params.ChatParams;
import com.tool4j.entity.vo.DMessage;
import com.tool4j.mapper.AiChatLogMapper;
import com.tool4j.service.AiChatLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class AiChatLogServiceImpl extends ServiceImpl<AiChatLogMapper, AiChatLog> implements AiChatLogService {

    @Autowired
    private AiChatLogMapper chatLogMapper;

    @Override
    public void saveLog(ChatParams params) {
        AiChatLog log = new AiChatLog();
        log.setId(Long.parseLong(params.getChatId()));
        log.setInput(params.getContent());
        log.setSessionId(Long.parseLong(params.getSessionId()));
        chatLogMapper.insert(log);
    }

    @Override
    public void updateLog(String chatId, String output) {
        AiChatLog log = chatLogMapper.selectById(Long.parseLong(chatId));
        if (log.getOutput() != null) {
            log.setOutput(log.getOutput() + output);
        } else {
            log.setOutput(output);
        }
        chatLogMapper.updateById(log);
    }

    @Override
    public List<DMessage> findList(Long sessionId) {
        LambdaQueryWrapper<AiChatLog> query = Wrappers.lambdaQuery(AiChatLog.class)
                .eq(AiChatLog::getSessionId, sessionId);
        List<AiChatLog> chatLogs = chatLogMapper.selectList(query);
        List<DMessage> result = new ArrayList<>();
        for (AiChatLog chatLog : chatLogs) {
            if (StrUtil.isNotBlank(chatLog.getInput())) {
                result.add(new DMessage()
                        .setRole("user")
                        .setContent(chatLog.getInput()));
            }
            if (StrUtil.isNotBlank(chatLog.getOutput())) {
                result.add(new DMessage()
                        .setRole("assistant")
                        .setContent(chatLog.getOutput()));
            }
        }
        return result;
    }

}
